package org.dylan.bdf.system.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dylan.bdf.system.entity.Role;
import org.dylan.bdf.system.service.SystemService;
import org.dylan.common.model.BaseQueryParam;
import org.dylan.common.model.BaseQueryParam.MatchType;
import org.dylan.common.paging.PageData;
import org.dylan.common.paging.PageRequest;
import org.dylan.web.model.JsonResult;
import org.dylan.web.plugin.omui.ModelConverter;
import org.dylan.web.plugin.omui.model.GridModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/system/role")
public class RoleController {

	@Autowired
	private SystemService systemService;

	@RequestMapping(value = { "", "list" })
	public String list() {
		return "/system/role";
	}

	@RequestMapping("gridData")
	@ResponseBody
	public GridModel<Role> gridData(HttpServletRequest request,
			@RequestParam(required = false) Integer start,
			@RequestParam(required = false) Integer limit,
			@RequestParam(required = false) Map<String, Object> params) {
		if (start == null) {
			start = 0;
		}
		if (limit == null) {
			limit = 15;
		}
		PageRequest pageRequest = new PageRequest(start, limit);
		pageRequest.addParam(new BaseQueryParam().field("name")
				.matchType(MatchType.LIKE_ANYWHERE)
				.value(params.get("name")));
		PageData<Role> pageData = systemService.findRoleByPage(pageRequest);
		GridModel<Role> model = ModelConverter.convertToGridModel(pageData);
		return model;
	}

	@RequestMapping("edit")
	public String edit(HttpServletRequest request,
			@RequestParam(required = false) String id, ModelMap model) {
		Role role = null;
		if (StringUtils.isNotBlank(id)) {
			role = systemService.findRole(id);
		}
		model.addAttribute("model", role);
		return "system/role-form";
	}

	@RequestMapping("ajaxSave")
	@ResponseBody
	public JsonResult<String> ajaxSave(Role role) {
		systemService.saveRole(role);
		return JsonResult.str();
	}
}
